const jwt = require('jsonwebtoken')
const signkey = 'books_mark'

/**
 * 生成随机ID
 * @param {number} len ID长度
 * @returns {string} ID
 */
const useCreateID = (len = 8) => {
  let id = ''
  for (let i = 0; i < len; i++) {
    id += Math.floor(Math.random() * 10)
  }
  return id
}

/**
 * 设置token
 * @param {object} params 参数
 * @param {string} expiresIn 过期时间
 * @returns {string} token
 */
const useSetToken = (params, expiresIn = '72h') => jwt.sign(params, signkey, { expiresIn })

/**
 * 验证token
 * @param {string} token token
 * @returns {object} token
 * @returns {null} null
 */
const useVerToken = (token) => {
  let resolve = null
  jwt.verify(token, signkey, (err, data) => {
    resolve = data || null
  })
  return resolve
}

/**
 * 处理书签数据
 * @param {*} result
 * @returns
 */
const useBooksData = (result) => {
  const booksList = []

  result.map((item) => {
    const {
      book_id,
      book_url,
      book_name,
      book_desc,
      books_id,
      books_desc,
      books_name,
      books_status,
      book_status
    } = item

    // 查找书签签列表
    const index = booksList.findIndex((v) => v?.id === books_id)

    const book = {
      id: book_id,
      name: book_name,
      url: book_url,
      description: book_desc,
      parent_id: books_id,
      status: book_status === 1 ? 'public' : 'private'
    }

    // 判断书签列表是否在 booksList
    if (index === -1) {
      booksList.push({
        id: books_id,
        name: books_name,
        description: books_desc,
        status: books_status === 1 ? 'public' : 'private',
        children: [book]
      })
    } else {
      booksList[index]?.children.push(book)
    }
  })

  return booksList
}

/**
 * 验证是否登录
 * @param {string} tokens
 * @returns {boolean}
 */
const useLogin = (tokens) => {
  const token = tokens?.split(' ')[1] || ''
  return useVerToken(token) ? true : false
}

module.exports = {
  useCreateID,
  useSetToken,
  useVerToken,
  useBooksData,
  useLogin
}
